<template>
    <modal :value="value" @on-ok="save" @on-visible-change="visibleChange"
           :draggable="!$config.mask"
           :mask="$config.mask"
           :mask-closable="!$config.mask" :width="592">
        <p slot="header">
            更换头像
        </p>
        <div class="cropper-wrapper">
            <div class="img-box">
                <img class="cropper-image" :id="imgId" alt="">
            </div>
            <div class="right-con">
                <div v-if="preview" class="preview-box" :id="previewId"></div>
                <div class="button-box">
                    <Upload :before-upload="beforeUpload" action=""
                            accept="image/jpg,image/jpeg,image/gif,image/png">
                        <Button style="width: 150px;" type="primary" icon="md-cloud-upload">选择图像</Button>
                    </Upload>
                    <div v-show="insideSrc">
                        <Button type="primary" @click="rotate">
                            <Tooltip content="旋转">
                                <Icon :size="18" type="md-refresh" />
                            </Tooltip>
                        </Button>
                        <Button type="primary" @click="shrink">
                            <Tooltip content="缩小">
                                <Icon :size="18" type="md-remove" />
                            </Tooltip>
                        </Button>
                        <Button type="primary" @click="magnify">
                            <Tooltip content="放大">
                                <Icon :size="18" type="md-add" />
                            </Tooltip>
                        </Button>
                        <Button type="primary" @click="scale('X')">
                            <Tooltip content="水平翻转">
                                <Icon :size="18" type="md-swap" />
                            </Tooltip>
                        </Button>
                        <Button type="primary" @click="move(0, -moveStep)">
                            <Tooltip content="上移">
                                <Icon :size="18" type="md-arrow-round-up" />
                            </Tooltip>
                        </Button>
                        <Button type="primary" @click="scale('Y')">
                            <Tooltip content="垂直翻转">
                                <Icon :size="18" style="transform: rotateZ(90deg);" type="md-swap" />
                            </Tooltip>
                        </Button>
                        <Button type="primary" @click="move(-moveStep, 0)">
                            <Tooltip content="左移">
                                <Icon :size="18" type="md-arrow-round-back" />
                            </Tooltip>
                        </Button>
                        <Button type="primary" @click="move(0, moveStep)">
                            <Tooltip content="下移">
                                <Icon :size="18" type="md-arrow-round-down" />
                            </Tooltip>
                        </Button>
                        <Button type="primary" @click="move(moveStep, 0)">
                            <Tooltip content="右移">
                                <Icon :size="18" type="md-arrow-round-forward" />
                            </Tooltip>
                        </Button>
                    </div>
                </div>
            </div>
        </div>
        <div slot="footer">
            <Button @click="cancel" icon="md-close">取消</Button>
            <Button @click="save" type="primary" icon="md-checkmark" :disabled="disabled">确定</Button>
        </div>
    </modal>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.min.css';
import Ajax from '@/lib/ajax';
import Util from '@/lib/util';

@Component({
    components: {},
})
export default class AvatarChange extends AbpBase {
    name: string = 'AvatarChange';

    @Prop({type: Boolean, default: false}) value: boolean;

    src: string = '';
    preview: boolean = true;
    moveStep: number = 4;
    cropper: any = null;
    insideSrc: string = '';
    disabled: boolean = false;
    file: any = null;

    get imgId() {
        return `cropper${(this as any)._uid}`;
    }

    get previewId() {
        return `cropper_preview${(this as any)._uid}`;
    }

    @Watch('src')
    srcChange(src: string) {
        this.replace(src);
    }

    @Watch('insideSrc')
    insideSrcChange(src: string) {
        this.replace(src);
    }

    beforeUpload(file) {
        const format = ['jpg', 'jpeg', 'gif', 'png'];
        const _file_format = file.name.split('.').pop().toLocaleLowerCase();
        const checked = format.some(item => item.toLocaleLowerCase() === _file_format);
        if (!checked) {
            this.$Message.error({
                background: true,
                content: '图像格式不正确，仅支持JPG、PNG、GIF格式',
                duration: this.$config.duration,
            })
            return false;
        }
        if (file.size > 10 * 1024 * 1024) {
            this.$Message.error({
                background: true,
                content: '原始图像大小超出 10MB 的限制',
                duration: this.$config.duration,
            })
            return false;
        }
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (event) => {
            this.insideSrc = (event.srcElement as any).result;
        };
        return false;
    }

    replace(src) {
        this.cropper.replace(src);
        this.insideSrc = src;
    }

    rotate() {
        this.cropper.rotate(90);
    }

    shrink() {
        this.cropper.zoom(-0.1);
    }

    magnify() {
        this.cropper.zoom(0.1);
    }

    scale(d) {
        this.cropper[`scale${d}`](-this.cropper.getData()[`scale${d}`]);
    }

    move(...arg) {
        this.cropper.move(...arg);
    }

    async save() {
        if (!this.insideSrc) {

            this.$Message.error({
                background: true,
                content: '请选择要裁剪的图像后再操作',
                duration: this.$config.duration,
            });
        } else {
            this.cropper.getCroppedCanvas().toBlob(async blob => {
                const formData = new FormData();
                const guid = Util.guid();
                formData.append('croppedImg', blob);
                formData.append('fileType', 'image/png');
                formData.append('fileName', 'ProfilePicture');
                formData.append('fileToken', guid);
                await Ajax.put('/api/Profile/UploadProfilePicture', formData);
                await this.$store.dispatch({
                    type: 'app/updateProfilePicture',
                    data: {
                        fileToken: guid,
                    },
                });
                this.$Message.success({
                    background: true,
                    content: '您的头像已修改成功',
                    duration: this.$config.duration,
                });
                this.$emit('save-success');
                this.$emit('input', false);
            });
        }
    }

    mounted() {
        this.$nextTick(() => {
            let dom: any = document.getElementById(this.imgId);
            this.cropper = new Cropper(dom, {
                preview: `#${this.previewId}`,
                checkCrossOrigin: true,
                viewMode: 1,
                aspectRatio: 1 / 1,
            });
        });
    }

    visibleChange(value: boolean) {
        if (!value) {
            this.reset();
            this.$emit('input', value);
        }
    }

    reset() {
    }

    cancel() {
        this.$emit('input', false);
    }
}
</script>

<style lang="less" scoped>
@import './styles/avatar-change.less';
</style>
